﻿using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace BatBomRemover
{
    public class MainForm : Form
    {
        private ListView listView;
        private Button btnSelectFiles;
        private Button btnRemoveBom;
        private TextBox logBox;

        public MainForm()
        {
            Text = "批处理文件 BOM 移除工具";
            Width = 700;
            Height = 500;
            FormBorderStyle = FormBorderStyle.FixedDialog;
            MaximizeBox = false;
            StartPosition = FormStartPosition.CenterScreen;

            btnSelectFiles = new Button
            {
                Text = "选择 .bat 文件...",
                Left = 20,
                Top = 20,
                Width = 150,
                Height = 30
            };
            btnSelectFiles.Click += BtnSelectFiles_Click;

            btnRemoveBom = new Button
            {
                Text = "开始去除 BOM",
                Left = 190,
                Top = 20,
                Width = 150,
                Height = 30,
                Enabled = false
            };
            btnRemoveBom.Click += BtnRemoveBom_Click;

            listView = new ListView
            {
                Left = 20,
                Top = 70,
                Width = 640,
                Height = 280,
                View = View.Details,
                FullRowSelect = true,
                GridLines = true
            };
            listView.Columns.Add("文件路径", 500);
            listView.Columns.Add("状态", 120);

            logBox = new TextBox
            {
                Left = 20,
                Top = 370,
                Width = 640,
                Height = 70,
                Multiline = true,
                ScrollBars = ScrollBars.Vertical,
                ReadOnly = true
            };

            Controls.Add(btnSelectFiles);
            Controls.Add(btnRemoveBom);
            Controls.Add(listView);
            Controls.Add(logBox);

            // 支持拖放文件
            AllowDrop = true;
            DragEnter += (s, e) =>
            {
                if (e.Data.GetDataPresent(DataFormats.FileDrop))
                    e.Effect = DragDropEffects.Copy;
            };
            DragDrop += (s, e) =>
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                AddFiles(files.Where(f => f.EndsWith(".bat", StringComparison.OrdinalIgnoreCase)).ToArray());
            };
        }

        private void BtnSelectFiles_Click(object sender, EventArgs e)
        {
            using var ofd = new OpenFileDialog
            {
                Title = "选择要去除 BOM 的 BAT 文件",
                Filter = "批处理文件 (*.bat)|*.bat",
                Multiselect = true
            };

            if (ofd.ShowDialog() == DialogResult.OK)
                AddFiles(ofd.FileNames);
        }

        private void AddFiles(string[] files)
        {
            foreach (var file in files)
            {
                if (listView.Items.Cast<ListViewItem>().Any(i => i.Text == file))
                    continue;

                var item = new ListViewItem(file);
                item.SubItems.Add("待处理");
                listView.Items.Add(item);
            }

            if (listView.Items.Count > 0)
                btnRemoveBom.Enabled = true;
        }

        private void BtnRemoveBom_Click(object sender, EventArgs e)
        {
            int fixedCount = 0;
            logBox.Clear();

            foreach (ListViewItem item in listView.Items)
            {
                string file = item.Text;
                try
                {
                    byte[] bytes = File.ReadAllBytes(file);

                    // 检查 BOM (EF BB BF)
                    if (bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)
                    {
                        byte[] newBytes = new byte[bytes.Length - 3];
                        Array.Copy(bytes, 3, newBytes, 0, newBytes.Length);

                        string backup = file + ".bak";
                        if (!File.Exists(backup))
                            File.Copy(file, backup, true);

                        File.WriteAllBytes(file, newBytes);

                        item.SubItems[1].Text = "✅ 已移除";
                        logBox.AppendText($"已移除 BOM: {Path.GetFileName(file)}\r\n");
                        fixedCount++;
                    }
                    else
                    {
                        item.SubItems[1].Text = "✔ 无 BOM";
                    }
                }
                catch (Exception ex)
                {
                    item.SubItems[1].Text = "❌ 失败";
                    logBox.AppendText($"错误: {file} - {ex.Message}\r\n");
                }
            }

            MessageBox.Show($"处理完成，共 {fixedCount} 个文件移除 BOM。", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
